<?php /** @noinspection ALL */

/**
 * @link https://www.len168.com
 * @copyright Copyright (c) 19-5-13 len168.com
 * @author toshcn <toshcn@foxmail.com>
 */

namespace api\controllers;

use Yii;
use common\models\User;
use yii\web\UploadedFile;
use common\models\ProfileForm;
use common\models\UploadForm;
use common\models\UserFollower;

/**
 * 用户控制器
 * UserController controller
 */
class UserController extends AuthController
{
    /**
     * 获取用户信息
     * @return mixed
     * @throws \Throwable
     */
    public function actionInfo()
    {
        $uid = (int) Yii::$app->getRequest()->get('uid');

        if ($uid && ($user = User::findOne($uid))) {
            // 返回用户资料
            $data = $user->userInfo();

            return Yii::$app->api->success($data);
        }
        return Yii::$app->api->success([]);
    }

    /**
     * 获取当前登录用户信息
     * @return mixed
     * @throws \Throwable
     */
    public function actionCurrentInfo()
    {
        if ($user = Yii::$app->getUser()->getIdentity()) {
            // 返回用户资料
            return Yii::$app->api->success($user->getCurrentUserInfo());
        }
        return Yii::$app->api->error();
    }

    /**
     * 头像上传
     */
    public function actionEditAvatar()
    {
        $this->validateIsPost();
        $model = new UploadForm(['scenario' => 'image']);
        $model->imageFile = UploadedFile::getInstanceByName('imageFile');
        if ($res = $model->uploadAvatar(Yii::$app->getUser()->getId())) {
            $profile = new ProfileForm();
            $profile->avatar = $res['url'];

            if ($profile->editAvatar()) {
                return Yii::$app->api->success(['avatar' => $res['url']]);
            }
            return Yii::$app->api->error('修改失败');
        }

        $message = $model->getFirstError('imageFile');
        return Yii::$app->api->error($message ? $message : '上传失败');
    }
}
